package com.heitaoking.blog.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.heitaoking.blog.dao.BlogDao;
import com.heitaoking.blog.entity.Blog;

/*
 * 博文内容添加Servlet类
 * 
 * */
public class Seebowen extends HttpServlet {
	// java类的身份证，主要用于版本控制
	/*
	 * serialVersionUID的作用是序列化的时候保持版本的兼容性，即是在版本升级反序列化时 仍然保持对象的唯一性*
	 */

	private static final long serialVersionUID = 1L;
	// 初始化DAO对象
	BlogDao dao = null;

	/*
	 * 初始化对象，将初始化DAO对象的方法放入init()方法中，并且确保dao只能创建一次
	 */
	public void init() throws ServletException {
		// 初始化dao对象
		dao = new BlogDao();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 设置编码集为“UTF-8”（避免乱码）
		request.setCharacterEncoding("utf-8");
		// 创建博客内容视图对象（用于封装查询到的博客内容信息）
		Blog blog = new Blog();

		try {
			// 调用dao中新增博客的方法
			ArrayList<Blog> blogList = (ArrayList<Blog>) dao.queryBlog(blog);
			// 将结果保存到request中
			request.setAttribute("blogList", blogList);
			// request.setAttribute("message", "发表成功");
			// 执行BloggerQueryServlet中的查询方法，更新博客信息表
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/yemianJSP/DH-shouye.jsp");
			// 将请求转发给servlet
			rd.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			// 将结果保存到request
			request.setAttribute("message", "查看失败");
			// 执行查询方法，更新博客信息表
			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					"/jsp/yemianJSP/DH-bowen guanli.jsp.jsp");
			// 将请求转发给servlet
			rd.forward(request, response);
		}

	}

}
